package cn.shequren.communityPeople.startup.model;

import android.content.Context;

import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.net.retrofit.ApiException;
import com.jz.community.basecomm.net.retrofit.ApiUtils;
import com.jz.community.basecomm.net.retrofit.HttpRxObservable;
import com.jz.community.basecomm.net.retrofit.RxLoadingWrapper;
import com.jz.community.basecomm.net.rxandroid.OnLoadListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.trello.rxlifecycle2.components.support.RxFragmentActivity;

import cn.shequren.communityPeople.startup.bean.StartUpAdvInfo;
import cn.shequren.communityPeople.startup.net.StartUpApi;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by Tony.Fan on 2018/3/23 17:45
 */
public class StartUpModelImpl implements StartUpModel {

    private Context mContext;

    public StartUpModelImpl(Context context) {
        mContext = context;
    }

    @Override
    public void requestStartUpAdv(OnLoadListener<StartUpAdvInfo> onLoadListener) {
        RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(mContext);
        Observable<StartUpAdvInfo> advInfoObservable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, StartUpApi.class)
                .getStartUpAdvInfo(region.getCode(), "1"));
        new RxLoadingWrapper<StartUpAdvInfo>(mContext, false)
                .execute(advInfoObservable)
                .subscribe(startUpAdvInfo -> {
                    if (startUpAdvInfo == null) {
                        return;
                    }
                    onLoadListener.onSuccess(startUpAdvInfo);
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(throwable.toString(), ApiException.handleException(throwable).code);
                    }
                });
    }
}
